package org.example.springbootwebexample.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.springbootwebexample.pojo.Result;
import org.example.springbootwebexample.utils.JwtUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
        登录校验过滤器
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //1.获取请求url
        String url = request.getRequestURL().toString();

        //2.判断请求url中是否包含login，如果包含，说明是登陆操作，放行
        if(url.contains("login")){
            log.info("登录请求，直接放行");
            chain.doFilter(request, response);
            return;
        }

        //3.获取请求头中的令牌(token)
        String jwt = request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，返回错误结果(未登录)
        //if(jwt == null || "".equals(jwt))
        if(!StringUtils.hasLength(jwt)){
            log.info("获取到jwt令牌为空，返回错误结果");
            Result result = Result.error("NOT_LOGIN");

            String notLogin = JSONObject.toJSONString(result);

            response.getWriter().write(notLogin);
            return;
        }

        //5.解析token，如果解析失败，返回错误结果(未登录)
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //throw new RuntimeException(e);
            log.info("解析令牌失败，返回错误结果");
            Result result = Result.error("NOT_LOGIN");

            String notLogin = JSONObject.toJSONString(result);

            response.getWriter().write(notLogin);
            return;

        }

        //6.放行
        log.info("令牌合法，放行");
        chain.doFilter(request,response);

    }
}
